package com.tj.jinzao.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.internal.LinkedTreeMap;
import com.tandong.bottomview.view.BottomView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tj.jinzao.R;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.base.IBaseView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.model.HealthReport;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.presenter.HealthReportPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Util;
import com.tj.jinzao.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


/**
 * 健康报告详情
 * Created by wjy on 2019/1/5.
 */
public class HealthReportDetailActivity extends BaseActivity implements IBaseView<List<HealthReport>> {

    @BindView(R.id.tv_health)
    TextView mHealthView;
    @BindView(R.id.tv_date)
    TextView mDateView;
    @BindView(R.id.tv_score)
    TextView mScoreView;
    @BindView(R.id.iv_bar)
    ImageView mBarView;
    @BindView(R.id.image_f)
    ImageView image_f;
    @BindView(R.id.image_z)
    ImageView image_z;
    @BindView(R.id.tv_face_desc)
    TextView mFaceDescView;
    @BindView(R.id.tv_tongue_desc)
    TextView mTongueDescView;
    @BindView(R.id.tv_health_status)
    TextView mHealthStatusView;
    @BindView(R.id.ll_case_layout)
    LinearLayout mContentLayout;
    private int mBarWidth, mBarHeight;
    private BottomView bottomView;
    private IWXAPI api;
    private void showPopWindow(){
        bottomView=new BottomView(HealthReportDetailActivity.this, R.style.BottomViewTheme_Defalut, R.layout.share_item_pop);
        bottomView.setAnimation(R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(false);
        TextView exit=bottomView.getView().findViewById(R.id.exit);
        LinearLayout lay_1=bottomView.getView().findViewById(R.id.lay_1);
        LinearLayout lay_2=bottomView.getView().findViewById(R.id.lay_2);
        LinearLayout lay_3=bottomView.getView().findViewById(R.id.lay_3);
        LinearLayout lay_4=bottomView.getView().findViewById(R.id.lay_4);
        LinearLayout lay_5=bottomView.getView().findViewById(R.id.lay_5);
        LinearLayout lay_6=bottomView.getView().findViewById(R.id.lay_6);
        lay_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Util.shareWeb(HealthReportDetailActivity.this,api, SendMessageToWX.Req.WXSceneSession);
                bottomView.dismissBottomView();
            }
        });
        lay_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(HealthReportDetailActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(HealthReportDetailActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                //初始化一个 WXTextObject 对象，填写分享的文本内容
                Util.shareWeb(HealthReportDetailActivity.this,api,SendMessageToWX.Req.WXSceneTimeline);
                bottomView.dismissBottomView();
            }
        });
        lay_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(HealthReportDetailActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(HealthReportDetailActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();
            }
        });

    }

    private HealthReportPresenter mPresenter;

    public static void start(Context context, int reportId) {
        context.startActivity(new Intent(context, HealthReportDetailActivity.class)
                .putExtra("reportId", reportId));
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    protected int getRightButtonResId() {
        return R.mipmap.icon_share;
    }

    @Override
    protected void clickRightButton() {
        //todo share
        showPopWindow();
    }


    @Override
    public int getLayoutResource() {
        return R.layout.activity_face_detail;
    }

    @Override
    protected void setupView() {
        super.setupView();
        api = WXAPIFactory.createWXAPI(this, Constant.WX_APPID);
        api.registerApp(Constant.WX_APPID);

        mBarWidth = Constant.SCREEN_WIDTH - Utils.dpToPx(32, getResources());
        mBarHeight = mBarWidth * 32 / 351;
        int reportId = getIntent().getIntExtra("reportId", 0);
        if (reportId == 0) {
            finish();
            return;
        }
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(mBarWidth, mBarHeight);
        layoutParams.setMargins(0, Utils.dpToPx(50, getResources()), 0, 0);
        mBarView.setLayoutParams(layoutParams);
        mPresenter = new HealthReportPresenter(this);
        mPresenter.getReportDetail(reportId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
        detachView();
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    public Activity getContext() {
        return this;
    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }


    //根据id获取健康报告分数
    private void getReportScore(){
        addSubscription(mApiService.getHealthScore(Long.parseLong(String.valueOf(getIntent().getIntExtra("reportId", 0)))), new SubscriberCallBack<String>(HealthReportDetailActivity.this) {

            @Override
            protected void onSuccess(String report) {
                mScoreView.setText(report + "分");


            }

            @Override
            protected void onFailure(ResultResponse response) {
            }

            @Override
            protected void onStringSuccess(String face_photo_url, String tongue_photo_url) {
            }
        });

    }
    //根据ID获取健康报告信息
    private void getReport(int id){
        addSubscription(mApiService.getHealthReportId(Long.parseLong(String.valueOf(id))), new SubscriberCallBack<HealthReport>(HealthReportDetailActivity.this) {

            @Override
            protected void onSuccess(HealthReport report) {

            }

            @Override
            protected void onFailure(ResultResponse response) {
            }

            @Override
            protected void onStringSuccess(String face_photo_url, String tongue_photo_url) {
                if(face_photo_url!=null&&face_photo_url.contains("http")){
                    Glide.with(HealthReportDetailActivity.this).load(face_photo_url).into(image_z);
                }else {
                    Glide.with(HealthReportDetailActivity.this).load(Constant.IMAGE_PREFIX + face_photo_url).into(image_z);
                }
                if(tongue_photo_url!=null&&tongue_photo_url.contains("http")){
                    Glide.with(HealthReportDetailActivity.this).load(tongue_photo_url).into(image_f);
                }else {
                    Glide.with(HealthReportDetailActivity.this).load(Constant.IMAGE_PREFIX + tongue_photo_url).into(image_f);
                }
            }
        });

    }



    @Override
    public void onRequestSuccess(List<HealthReport> reports) {
        if(reports.size()<=0){
            return;
        }
        getReport(reports.get(0).getId());
        getReportScore();
        try {
            HealthReport report = reports.get(0);
            mDateView.setText(report.getDisplay_time().split(" ")[0]);
            mHealthView.setText(report.getHealth_status_text());
            mScoreView.setText(report.getHealth_score() + "分");
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins((int)(report.getHealth_score() * mBarWidth / 100 - Utils.dpToPx(62, getResources())), 0, 0, 0);
            mScoreView.setLayoutParams(layoutParams);
            HealthReport.FaceResultBean faceResultBean = report.getFace_result();
            mFaceDescView.setText(HealthReportPresenter.FACE_COLOR[faceResultBean.getFaceColor()] +
                    "," + HealthReportPresenter.FACE_GLOSS[faceResultBean.getFaceGloss()] +
                    "," + HealthReportPresenter.LIP_COLOR[faceResultBean.getLipColor()]);
            HealthReport.TongueResultBean tongueResultBean = report.getTongue_result();
            mTongueDescView.setText(HealthReportPresenter.TONGUE_COAT_COLOR[tongueResultBean.getTongueCoatColor()] +
                    "," + HealthReportPresenter.TONGUE_COAT_THICKNESS[tongueResultBean.getTongueCoatThickness()]);
            StringBuilder stringBuilder = new StringBuilder();
            mContentLayout.removeAllViews();
            for (HealthReport.SymptomsBean bean : report.getSymptoms()) {
                if (stringBuilder.length() != 0) stringBuilder.append("，");
                stringBuilder.append(bean.getName());

            }
            LinkedTreeMap<String, LinkedTreeMap> map = (LinkedTreeMap) report.getSolutions().getSymptom_definition();
            for (String key : map.keySet()) {
//                addLine();
                String s="";
//                addTitle(key);
                LinkedTreeMap<String, ArrayList<String>> keyMap = map.get(key);
                ArrayList<String> content = keyMap.get("content");
                for (String c : content) {
                    if(s==null||s.equals("")){
                        s=s+c;
                    }else {
                        s=s+","+c;
                    }


                }
                addText(s);
            }
            addLine();



            LinkedTreeMap<String, LinkedTreeMap> map1 = (LinkedTreeMap) report.getSolutions().getHealth_guidance();
            if(map1.size()>0){
                addTitle("保健原则");
            }
            for (String key : map1.keySet()) {
//                addLine();
                String s="";
                LinkedTreeMap<String, ArrayList<String>> keyMap = map1.get(key);
                ArrayList<String> content = keyMap.get("content");
                for (String c : content) {
                    if(s==null||s.equals("")){
                        s=s+c;
                    }else {
                        s=s+","+c;
                    }

                }
                addText(s);
            }
            addLine();


            LinkedTreeMap<String, LinkedTreeMap> map2 = (LinkedTreeMap) report.getSolutions().getHealth_guidance();
            if(map2.size()>0){
                addTitle("起居指导");
            }
            for (String key : map2.keySet()) {
//                addLine();
                String s="";
                LinkedTreeMap<String, ArrayList<String>> keyMap = map2.get(key);
                ArrayList<String> content = keyMap.get("content");
                for (String c : content) {
                    if(s==null||s.equals("")){
                        s=s+c;
                    }else {
                        s=s+","+c;
                    }

                }
                addText(s);
            }
            addLine();

            LinkedTreeMap<String, LinkedTreeMap> map4 = (LinkedTreeMap) report.getSolutions().getDiet_therapy();
            if(map4.size()>0){
                addTitle("药膳养生");
            }
            for (String key : map4.keySet()) {
//                addLine();
                String s="";
                LinkedTreeMap<String, ArrayList<String>> keyMap = map4.get(key);
                ArrayList<String> content = keyMap.get("content");
                for (String c : content) {
                    if(s==null||s.equals("")){
                        s=s+c;
                    }else {
                        s=s+","+c;
                    }

                }
                addText(s);
            }
            addLine();

            LinkedTreeMap<String, LinkedTreeMap> map5 = (LinkedTreeMap) report.getSolutions().getHerb_tea();
            if(map5.size()>0){
                addTitle("茶饮养生");
            }
            for (String key : map5.keySet()) {
//                addLine();
                String s="";
                LinkedTreeMap<String, ArrayList<String>> keyMap = map5.get(key);
                ArrayList<String> content = keyMap.get("content");
                for (String c : content) {
                    if(s==null||s.equals("")){
                        s=s+c;
                    }else {
                        s=s+","+c;
                    }

                }
                addText(s);
            }
            addLine();



            LinkedTreeMap<String, LinkedTreeMap> map3 = (LinkedTreeMap) report.getSolutions().getMassage();
            if(map3.size()>0){
                addTitle("中国功法");
            }
            for (String key : map3.keySet()) {
//                addLine();
                String s="";
                LinkedTreeMap<String, ArrayList<String>> keyMap = map3.get(key);
                ArrayList<String> content = keyMap.get("content");
                for (String c : content) {
                    if(s==null||s.equals("")){
                        s=s+c;
                    }else {
                        s=s+","+c;
                    }
                }
                addText(s);
            }

            mHealthStatusView.setText(stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addTitle(String title) {
        View view = getLayoutInflater().inflate(R.layout.report_title, null);
        TextView textView = view.findViewById(R.id.tv_title);
        textView.setText(title);
        mContentLayout.addView(view);
    }

    private void addText(String content) {
        View view = getLayoutInflater().inflate(R.layout.report_textview, null);
        TextView textView = view.findViewById(R.id.tv_desc);
        textView.setText(content);
        mContentLayout.addView(view);
    }

    private void addLine() {
        View view = getLayoutInflater().inflate(R.layout.report_line, null);
        mContentLayout.addView(view);
    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }
}
